/*******************************************************************************
 * Copyright 2020 huanggefan.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package action

import (
	"gitee.com/WisdomClassroom/bank/global"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"github.com/jinzhu/gorm"
	"time"
)

func DeleteQuestionBank(req *pb.DeleteQuestionBankRequest) *pb.DeleteQuestionBankResponse {
	resp := new(pb.DeleteQuestionBankResponse)
	var err error

	token := core.NewToken()
	err = token.UnpackToken(req.AuthToken, global.TokenCert)
	if err != nil {
		resp.Status = &pb.ResponseStatus{
			Code:    pb.ResponseStatusCode_OtherError,
			Message: "认证失败： " + err.Error(),
		}
		return resp
	}

	if token.Type != core.UserRoleTypeCodeRoot {
		resp.Status = &pb.ResponseStatus{
			Code:    pb.ResponseStatusCode_OtherError,
			Message: "没有权限",
		}
		return resp
	}

	bank := &models.BankModel{}
	err = global.DB.Where("uuid = ?", req.WillDeleteUUID).Not("deleted", true).First(bank).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			global.Logger.Debug("Find BankModel: record not found")
			resp.Status = &pb.ResponseStatus{
				Code:    pb.ResponseStatusCode_OtherError,
				Message: "题库不存在：" + req.WillDeleteUUID,
			}
		} else {
			global.Logger.Warning("Find BankModel error: " + err.Error())
			resp.Status = &pb.ResponseStatus{
				Code:    pb.ResponseStatusCode_OtherError,
				Message: "查找题库错误：" + err.Error(),
			}
		}
		return resp
	}

	now := time.Now().Unix()
	bank.Deleted = true
	bank.DeleteTime = now

	tx := global.DB.Begin()
	err = func() error {
		err = tx.Model(bank).Where("uuid = ?", bank.UUID).Updates(bank).Error
		if err != nil {
			tx.Rollback()
			return err
		}

		err = tx.Model(&models.BankManagerBindModel{}).
			Where("bank_uuid = ?", bank.UUID).
			Updates(models.BankManagerBindModel{Model: models.Model{Deleted: true, DeleteTime: now}}).Error
		if err != nil {
			tx.Rollback()
			return err
		}

		err = tx.Model(&models.BankCourseBindModel{}).
			Where("bank_uuid = ?", bank.UUID).
			Updates(models.BankCourseBindModel{Model: models.Model{Deleted: true, DeleteTime: now}}).Error
		if err != nil {
			tx.Rollback()
			return err
		}

		tx.Commit()
		return nil
	}()
	if err != nil {
		global.Logger.Warning("Delete BankModel error: " + err.Error())
		resp.Status = &pb.ResponseStatus{
			Code:    pb.ResponseStatusCode_OtherError,
			Message: "删除题库失败：" + err.Error(),
		}
		return resp
	}

	resp.Status = &pb.ResponseStatus{
		Code: pb.ResponseStatusCode_Suc,
	}
	return resp

}
